//
//  BSKLoginViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVUser+SNS.h>
#import <KVNProgress/KVNProgress.h>

#import "BSKLoginViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKSignupViewController.h"
#import "BSKUserCenterViewController.h"
#import "BSKForgetPasswordViewController.h"
#import "BSKStringCheck.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "BSKDBManager.h"
#import "UIViewController+BSKToast.h"
#import "IQKeyboardManager.h"

@interface BSKLoginViewController () <UITextFieldDelegate>
@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIScrollView *contentScrollView;
@property (strong, nonatomic) UIImageView *logoImageView;
@property (strong, nonatomic) UIView *emailView;
@property (strong, nonatomic) UIImageView *emailImageView;
@property (strong, nonatomic) UITextField *emailTextField;
@property (strong, nonatomic) UIView *passwordView;
@property (strong, nonatomic) UIImageView *passwordImageView;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UIButton *loginButton;
@property (strong, nonatomic) UIButton *forgetPasswordButton;
@property (strong, nonatomic) UIButton *signupButton;
@property (strong, nonatomic) UIView *horizontalLineView; // 第三方登录间隔线
@property (strong, nonatomic) UIButton *tencentQQButton;
@property (strong, nonatomic) UIButton *weChatButton;
@property (strong, nonatomic) UIButton *sinaWeiboButton;
@property (strong, nonatomic) NSArray *buttonArr;
@property (assign, nonatomic) NSInteger flag;
@property (strong, nonatomic) UIVisualEffectView * coverview;
@property (strong, nonatomic) UIImageView *imageView ;

@end

@implementation BSKLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self initializeUserInterface];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _flag = 0;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (_flag == 1) {
        UINavigationController * navVC = self.navigationController;
        NSMutableArray * array =[NSMutableArray arrayWithArray:navVC.viewControllers];
        [array removeObject:self];
        navVC.viewControllers = array;
    }
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (_flag == 0) {
        CGFloat contentHeight = 45 + 80 + 30 + 40 + 10 + 40 + 30 + 40 + 85 + 30 + 30 + 40 + 20;
        if (self.contentScrollView.height_sd <= contentHeight) {
            self.contentScrollView.contentSize = CGSizeMake(self.view.width, contentHeight);
        } else {
            self.contentScrollView.contentSize = self.contentScrollView.size_sd;
        }
        _flag = 2;
    }
}
#pragma mark - 初始化界面
- (void)initializeUserInterface {
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.coverview  = [[UIVisualEffectView alloc] initWithEffect:efect];
    self.imageView  = [[UIImageView alloc] initWithImage:[BSKTheme curentTheme].themeImage];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.contentScrollView = [[UIScrollView alloc] init];
    self.logoImageView = [[UIImageView alloc] init];
    self.emailView = [[UIView alloc] init];
    self.emailImageView = [[UIImageView alloc] init];
    self.emailTextField = [[UITextField alloc] init];
    self.passwordView = [[UIView alloc] init];
    self.passwordImageView = [[UIImageView alloc] init];
    self.passwordTextField = [[UITextField alloc] init];
    self.loginButton = [[UIButton alloc] init];
    self.coverview.frame = self.view.bounds;
    self.imageView.frame = self.view.bounds;
    
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.coverview];
    [self.view addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.contentScrollView];
    [self.contentScrollView addSubview:self.logoImageView];
    [self.contentScrollView addSubview:self.emailView];
    [self.emailView addSubview:self.emailImageView];
    [self.emailView addSubview:self.emailTextField];
    [self.contentScrollView addSubview:self.passwordView];
    [self.passwordView addSubview:self.passwordImageView];
    [self.passwordView addSubview:self.passwordTextField];
    [self.contentScrollView addSubview:self.loginButton];
    
    self.backButton.sd_layout.topSpaceToView(self.view, StatusBarHeight + 5)
    .leftSpaceToView(self.view, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.contentScrollView.sd_layout.topSpaceToView(self.view, NavigationBarHeight + StatusBarHeight)
    .rightEqualToView(_coverview)
    .leftEqualToView(_coverview)
    .bottomEqualToView(_coverview);
    self.contentScrollView.bounces = NO;
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    
    self.logoImageView.sd_layout.centerXEqualToView(self.contentScrollView)
    .topSpaceToView(self.contentScrollView, 45)
    .widthIs(80)
    .heightEqualToWidth();
    self.logoImageView.image = [UIImage imageNamed:@"logo"];
    self.logoImageView.layer.cornerRadius = 15;
    
    self.emailView.sd_layout.topSpaceToView(self.logoImageView, 30)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(40);
    self.emailView.layer.cornerRadius = 10;
    self.emailView.layer.masksToBounds = YES;
    
    UIView *lineView1 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView1];
    lineView1.sd_layout.topSpaceToView(self.emailView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView1.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.emailImageView.sd_layout.topSpaceToView(self.emailView, 5)
    .leftSpaceToView(self.emailView, 5)
    .widthIs(30)
    .heightIs(30);
    self.emailImageView.image = [UIImage imageNamed:@"email"];
    
    self.emailTextField.sd_layout.topEqualToView(self.emailView)
    .leftSpaceToView(self.emailImageView, 10)
    .rightEqualToView(self.emailView)
    .heightIs(40);
    self.emailTextField.delegate = self;
    self.emailTextField.borderStyle = UITextBorderStyleNone;
    self.emailTextField.placeholder = @"用户注册时的邮箱";
    [self.emailTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.emailTextField.textColor = [UIColor whiteColor];
    self.emailTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.emailTextField.returnKeyType = UIReturnKeyNext;
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    
    
    self.passwordView.sd_layout.topSpaceToView(self.emailView, 10)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView,30)
    .heightIs(40);
    self.passwordView.layer.cornerRadius = 10;
    self.passwordView.layer.masksToBounds = YES;
    
    UIView *lineView2 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView2];
    lineView2.sd_layout.topSpaceToView(self.passwordView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView2.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.passwordImageView.sd_layout.topSpaceToView(self.passwordView, 5)
    .leftSpaceToView(self.passwordView, 5)
    .widthIs(30)
    .heightIs(30);
    self.passwordImageView.image = [UIImage imageNamed:@"key"];
    
    self.passwordTextField.sd_layout.topEqualToView(self.passwordView)
    .leftSpaceToView(self.passwordImageView, 10)
    .rightEqualToView(self.passwordView)
    .heightIs(40);
    self.passwordTextField.delegate = self;
    self.passwordTextField.borderStyle = UITextBorderStyleNone;
    self.passwordTextField.placeholder = @"请输入密码";
    [self.passwordTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.passwordTextField.textColor = [UIColor whiteColor];
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordTextField.returnKeyType = UIReturnKeyDone;
    
    self.loginButton.sd_layout.centerXEqualToView(self.contentScrollView)
    .topSpaceToView(self.passwordView, 30)
    .widthRatioToView(self.passwordView, 1)
    .heightIs(40);
    self.loginButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginButton addTarget:self action:@selector(loginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.loginButton.layer.cornerRadius = 5;
    self.loginButton.layer.masksToBounds = YES;
    
    self.forgetPasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.signupButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.contentScrollView addSubview:self.forgetPasswordButton];
    [self.contentScrollView addSubview:self.signupButton];
    
    self.forgetPasswordButton.sd_layout.topSpaceToView(self.loginButton, 10)
    .leftEqualToView(self.loginButton)
    .heightIs(40)
    .widthIs(100);
    [self.forgetPasswordButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [self.forgetPasswordButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.forgetPasswordButton addTarget:self action:@selector(forgetPasswordAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.signupButton.sd_layout.topSpaceToView(self.loginButton, 10)
    .rightEqualToView(self.loginButton)
    .heightIs(40)
    .widthIs(100);
    [self.signupButton setTitle:@"用户注册" forState:UIControlStateNormal];
    [self.signupButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.signupButton addTarget:self action:@selector(signupAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *leftHorizontalLineView = [[UIView alloc] init];
    UIView *rightHorizontalLineView = [[UIView alloc] init];
    self.tencentQQButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tencentQQButton setImage:[UIImage imageNamed:@"qq_tencent"] forState:UIControlStateNormal];
    self.weChatButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.weChatButton.hidden = YES;
    self.sinaWeiboButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sinaWeiboButton setImage:[UIImage imageNamed:@"sina_weibo"] forState:UIControlStateNormal];
    self.buttonArr = @[_tencentQQButton, _weChatButton, _sinaWeiboButton];
    
    [self.contentScrollView addSubview:leftHorizontalLineView];
    [self.contentScrollView addSubview:rightHorizontalLineView];
    [self.contentScrollView addSubview:self.tencentQQButton];
    [self.contentScrollView addSubview:self.weChatButton];
    [self.contentScrollView addSubview:self.sinaWeiboButton];
    
    UILabel *flagLabel = [[UILabel alloc] init];
    [self.contentScrollView addSubview:flagLabel];
    
    flagLabel.sd_layout.centerXEqualToView(self.contentScrollView)
    .topSpaceToView(self.loginButton, 85)
    .widthIs(100)
    .heightIs(30);
    flagLabel.textAlignment = NSTextAlignmentCenter;
    flagLabel.textColor = [UIColor whiteColor];
    flagLabel.font = [UIFont systemFontOfSize:18];
    flagLabel.text = @"第三方登录";
    
    leftHorizontalLineView.sd_layout.centerYEqualToView(flagLabel)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(flagLabel, 0)
    .heightIs(1);
    leftHorizontalLineView.backgroundColor = [UIColor whiteColor];
    rightHorizontalLineView.sd_layout.centerYEqualToView(flagLabel)
    .leftSpaceToView(flagLabel, 0)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(1);
    rightHorizontalLineView.backgroundColor = [UIColor whiteColor];
    
    for (int index = 0; index < self.buttonArr.count; index++) {
        UIButton *button = self.buttonArr[index];
        button.tag = 1000 + index;
        button.sd_layout.topSpaceToView(flagLabel, 30)
        .centerXIs(self.view.centerX + (index - 1) * 80)
        .widthIs(40)
        .heightEqualToWidth();
        [button addTarget:self action:@selector(thirdLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    if (![AVOSCloudSNS isAppInstalledForType:AVOSCloudSNSQQ]) {
        self.tencentQQButton.hidden = YES;
    }
    if (![AVOSCloudSNS isAppInstalledForType:AVOSCloudSNSSinaWeibo]) {
        self.sinaWeiboButton.hidden = YES;
    }
	if(self.tencentQQButton.hidden&&self.sinaWeiboButton.hidden){
		flagLabel.hidden = YES;
		rightHorizontalLineView.hidden = YES;
		leftHorizontalLineView.hidden = YES;
	}
}


#pragma mark - 自定义方法
- (void)presentAlertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
}
- (void)loginButtonAction:(UIButton *)sender {
    [self.view endEditing:YES];
    sender.enabled = NO;
    __weak typeof(self) weakSlef = self;
    if (![self textFieldCheck:_emailTextField]) {
        sender.enabled = YES;
    } else if (![self textFieldCheck:_passwordTextField]) {
        sender.enabled = YES;
    } else {
        [KVNProgress show];
        [AVUser logInWithUsernameInBackground:_emailTextField.text password:_passwordTextField.text block:^(AVUser *user, NSError *error) {
            if (user != nil) {
                _flag = 1;
                [weakSlef updateLocalSQL];
                [[NSNotificationCenter defaultCenter]postNotificationName:BSKuserStatusChangeNotification object:nil];
                [KVNProgress dismiss];
                BSKUserCenterViewController * userCenter = [[BSKUserCenterViewController alloc]init];
                [weakSlef.navigationController pushViewController:userCenter animated:YES];
            } else {
                [KVNProgress dismiss];
                switch (error.code) {
                    case 1:
                        [weakSlef presentAlertWithMessage:@"登录失败次数超过限制，请稍候再试，或者通过忘记密码重设密码。"];
                        break;
                    case -1009:
                        [weakSlef presentAlertWithMessage:@"网络连接失败，请检查你的网络！"];
                        break;
                    default:
                        [weakSlef presentAlertWithMessage:@"用户名或密码错误！"];
                        break;
                }
                sender.enabled = YES;
            }
        }];
    }
}
- (void)forgetPasswordAction:(UIButton *)sender {
    BSKForgetPasswordViewController *forgetPswVC = [[BSKForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:forgetPswVC animated:YES];
}
- (void)signupAction:(UIButton *)sender {
    BSKSignupViewController *signupVC = [[BSKSignupViewController alloc] init];
    [self.navigationController pushViewController:signupVC animated:YES];
}
- (void)updateLocalSQL {
    BSKDBManager * manager = [[BSKDBManager alloc] init];
    [manager openDataBase:@"notedatabase.db"];
    NSString *userId = [AVUser currentUser].objectId;
    [manager updateDataToTable:@"type" Columnns:@[@[@"userID", userId]] condition:@"userID = 'null'"];
    [manager updateDataToTable:@"note" Columnns:@[@[@"userID", userId]] condition:@"userID = 'null'"];
    [manager.fmDatabase close];
}
- (void)appearAnimation {
    [UIView animateWithDuration:1 animations:^{
        self.contentScrollView.sd_layout.topSpaceToView(self.navView, 0);
    }];
}
#pragma mark - 第三方登录
- (void)thirdLoginAction:(UIButton *)sender {
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:@"1105523974" andAppSecret:@"vPhYCUeyvCEYurSE" andRedirectURI:nil];
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:@"220466121" andAppSecret:@"b881a75087325df0f00a4581ad6b6cdd" andRedirectURI:@""];
    NSString *platform;
    AVOSCloudSNSType snsType;
    switch (sender.tag) {
        case 1000: {
            snsType = AVOSCloudSNSQQ;
            platform = AVOSCloudSNSPlatformQQ;
            break;
        }
        case 1001: {
            snsType = AVOSCloudSNSWeiXin;
            platform = AVOSCloudSNSPlatformWeiXin;
            break;
        }
        case 1002: {
            snsType = AVOSCloudSNSSinaWeibo;
            platform = AVOSCloudSNSPlatformWeiBo;
            break;
        }
        default: {
            snsType = AVOSCloudSNSQQ;
            platform = AVOSCloudSNSPlatformQQ;
            break;
        }
    }
    __weak typeof(self) weakSelf = self;
    
//    [KVNProgress show];
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            [KVNProgress dismiss];
            [weakSelf MakeToast:@"登录失败" WithTime:1.5];
        } else {
            [AVUser loginWithAuthData:object platform:platform block:^(AVUser *user, NSError *error) {
                if (error) {
                    [AVOSCloudSNS logout:snsType];
                    [KVNProgress dismiss];
                    [weakSelf MakeToast:@"登录失败" WithTime:1.5];
                } else {
                    _flag = 1;
                    [weakSelf updateLocalSQL];
                    [[AVUser currentUser] setObject:object[@"username"] forKey:@"nickName"];
                    [[AVUser currentUser] setObject:object[@"avatar"] forKey:@"userHeader"];
                    [[AVUser currentUser] saveEventually:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [[NSNotificationCenter defaultCenter]postNotificationName:BSKuserStatusChangeNotification object:nil];
                            [KVNProgress dismiss];
                            BSKUserCenterViewController * userCenter = [[BSKUserCenterViewController alloc]init];
                            [weakSelf.navigationController pushViewController:userCenter animated:YES];
                        } else {
                            [AVOSCloudSNS logout:snsType];
                            [KVNProgress dismiss];
                            [weakSelf MakeToast:@"登录失败" WithTime:1.5];
                        }
                    }];
                }
            }];
        }
    } toPlatform:snsType];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.passwordTextField) {
        if (range.location > 15) {
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    if ([self textFieldCheck:textField]) {
        if (textField == self.emailTextField) {
            [self.passwordTextField becomeFirstResponder];
        }
        if (textField == self.passwordTextField) {
            [self loginButtonAction:nil];
        }
    }
    return YES;
}
- (BOOL)textFieldCheck:(UITextField *)textField {
    if (textField == self.emailTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"邮箱不能为空！" WithTime:1.5];
            return NO;
        } else if (![BSKStringCheck validateEmail:textField.text]) {
            [self MakeToast:@"邮箱格式不正确！" WithTime:1.5];
            return NO;
        }
        
    }
    if (textField == self.passwordTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"密码不能为空！" WithTime:1.5];
            return NO;
        }
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


@end
